package com.jzo2o.foundations.handler;

import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.service.HomeService;
import com.jzo2o.foundations.service.IRegionService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *  缓存同步
 *
 * @Author mr.wu
 * @Date 2025/1/19 15:57
 */
@Slf4j
@Component
public class SpringCacheSyncHandler {

    @Autowired
    private RedisTemplate redisTemplate;// 注入redis
    @Autowired
    private IRegionService regionService;// 注入服务
    @Autowired
    private HomeService homeService;

    /**
     * 刷新缓存
     */
    @XxlJob(value = "activeRegionCacheSync")
    public void activeRegionCacheSync() {

        log.info("[缓存预热-定时同步更新开通区域列表和区域对应的服务列表缓存]任务执行开始.......");
        //1. 获取开通区域列表缓存的RedisKey
        String redisKey = RedisConstants.CacheName.JZ_CACHE + "::" + "ACTIVE_REGIONS";

        //2. 根据RedisKey删除缓存
        redisTemplate.unlink(redisKey);

        //3. 查询表中已开通的区域列表最新数据添加到缓存中
        List<RegionSimpleResDTO> regionSimpleResDTOS = regionService.queryActiveRegionListCache();

        if(CollUtils.isEmpty(regionSimpleResDTOS)){
            return;
        }

        //4. 遍历区域列表
        for (RegionSimpleResDTO region : regionSimpleResDTOS) {
            Long regionId = region.getId();

            //4.1 获取服务列表缓存的RedisKey
            String serveRedisKey = RedisConstants.CacheName.SERVE_ICON + "::" + regionId;
            String serveTypeRedisKey = RedisConstants.CacheName.SERVE_TYPE + "::" + regionId;
            //4.2 根据redisKey删除缓存
            redisTemplate.unlink(serveRedisKey);
            redisTemplate.unlink(serveTypeRedisKey);
            //4.3 将表中符合要求的服务列表添加到缓存中
            homeService.firstPageServeList(regionId);
            homeService.serveTypeList(regionId);
        }

        //服务类型列表缓存



        log.info("[缓存预热-定时同步更新开通区域列表和区域对应的服务列表缓存]任务执行完毕.......");
    }

}
